#!/usr/bin/env python

from os3.utils.cache_man import CacheHandler

class LiWESession ( object ):
	def __init__ ( self, liwe ):
		self.liwe = liwe
		self.handler = None

		self.sess_base = "sess-%s" % liwe.cfg.get ( "site.id" )

		mode = self.liwe.cfg.get ( "session.mode" )
		try:
			self.timeout = int ( self.liwe.cfg.get ( "session.timeout", 60 ) )
		except:
			self.timeout = 60

		if not mode: mode = 'file'

		# Get Session parameters
		params = self.liwe.cfg.get ( "session.params", {} )

		# If Session mode == 'dbm', we inject the standard DBManager here
		if mode == 'dbm':
			params [ 'dbm' ] = self.liwe.dbm

		self.timeout *= 60 # from minutes to seconds

		self.handler = CacheHandler.create ( mode, params )

	def load ( self, sess_id ):
		return self.handler.get ( self._get_key ( sess_id ), {} )

	def save ( self, sess_id, data ):
		self.handler.set ( self._get_key ( sess_id ), data, self.timeout )

	def delete ( self, sess_id ):
		self.handler.delete ( self._get_key ( sess_id ) )	

	def _get_key ( self, sess_id ):
		return "%s-%s" % ( self.sess_base, sess_id )


